package cn.tp.ksoft.civil_driver.utils;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间戳转日期类型
 */
public class TimestampTypeAdapter implements JsonDeserializer<Date>,JsonSerializer<Date>{  
	private static final String FORMAT_DATE_PATTERN =Constants.FORMAT_DATE_COMMON_PATTERN;
	@Override
	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		String datejson = json.getAsJsonPrimitive().getAsString();
		try{
			// gson 转换的时候将后台的long类型转为了double类型
			Double timestamp = Double.parseDouble(datejson);
			return new Date(timestamp.longValue());
		}catch(NumberFormatException e){
			DateFormat format =  new SimpleDateFormat(FORMAT_DATE_PATTERN); 
			format.setLenient(false);
			try {
				format.parse(datejson);
			} catch (ParseException e1) {
				throw new IllegalArgumentException("解析日期出错!");
			}
		}
		return null;
	}
	@Override
	public JsonElement serialize(Date date, Type typeOfT,
			JsonSerializationContext context) {
		return new JsonPrimitive(date.getTime()+"");
	}
 }   